package com.fourforfo.fourmall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fourforfo.common.constant.ProductConstant;
import com.fourforfo.common.utils.R;
import com.fourforfo.fourmall.product.entity.*;
import com.fourforfo.fourmall.product.service.AttrAttrgroupRelationService;
import com.fourforfo.fourmall.product.service.AttrGroupService;
import com.fourforfo.fourmall.product.service.CategoryService;
import com.fourforfo.fourmall.product.vo.AttrRespVO;
import com.fourforfo.fourmall.product.vo.AttrVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fourforfo.common.utils.PageUtils;
import com.fourforfo.common.utils.Query;

import com.fourforfo.fourmall.product.dao.AttrDao;
import com.fourforfo.fourmall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.ws.Action;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupRelationService attrAttrgroupRelationService ;

    @Autowired
    AttrGroupService attrGroupService;

    @Autowired
    CategoryService categoryService;

    /**
     * 获取当前分组没有关联的所有属性
     * @param params
     * @param attrGroupId
     * @return
     */
    @Override
    public PageUtils queryPageNoAttrGroup(Map<String, Object> params, Long attrGroupId) {
        //1. 当前分组只能关联自己所属的分类里面的所有属性，每个属性都有其自己的categoryId
        AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrGroupId);
        if(attrGroupEntity==null){
            throw new NullPointerException("attrGroupEntity为空");
        }
        Long catelogId = attrGroupEntity.getCatelogId();
        if(catelogId==null){
            throw new NullPointerException("catelogId为空");
        }
//        List<AttrEntity> attrEntities = this.list(new QueryWrapper<AttrEntity>().eq("catelog_id",catelogId));
        //2. 当前分组只能关联别的分组没有引用的属性
        //2.1)当前分类下的其他分组,排除掉当前分组
        List<AttrGroupEntity> attrGroupEntities = attrGroupService.list(new QueryWrapper<AttrGroupEntity>().eq("catelog_id",catelogId));
        List<Long> attrGroupIds = attrGroupEntities.stream().map(item->{
            return item.getAttrGroupId();
        }).collect(Collectors.toList());

        //2.3)从该分类的所有属性中移除这些属性attr
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("catelog_id",catelogId).eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if(attrGroupIds!=null||attrGroupIds.size()>0){

            //2.2)其他分组的关联的属性
            List<AttrAttrgroupRelationEntity> relations=attrAttrgroupRelationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id",attrGroupIds));

            List<Long> attrIds = relations.stream().map(item->{
                return item.getAttrId();
            }).collect(Collectors.toList());
            if(attrIds!=null&&attrIds.size()>0){
                wrapper.notIn("attr_id",attrIds);
            }
        }

        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and((item)->{
                item.eq("attr_id",key).or().like("attr_name",key);
            });
        }

        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params),wrapper);
        return new PageUtils(page);
    }

    @Transactional
    @Override
    public List<AttrEntity> listAttrByGroup(Long attrGroupId) {
        List<AttrAttrgroupRelationEntity> relationEntitys = attrAttrgroupRelationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id",attrGroupId));
        List<Long> attrIds = relationEntitys.stream().map((relationEntity)->{
            return relationEntity.getAttrId();
        }).collect(Collectors.toList());
        if(attrIds!=null&&attrIds.size()>0){
            List<AttrEntity> results = this.listByIds(attrIds);
            return results;
        }


        return null;
    }

    /**
     * 删除所有attr以及attrattrGroupRelation信息
     * @param attrIds
     */
    @Override
    public void removeAttrAndAttrAttrGroupRelation(List<Long> attrIds) {
        this.removeByIds(attrIds);
        attrAttrgroupRelationService.removeByAttrIds(attrIds);
    }

    /**
     * 根据attrIds查出所有能被检索的attrIds，即search_type为1的attrs
     * @param attrIds
     * @return
     */
    @Override
    public List<Long> listSearchAttrsByIds(List<Long> attrIds) {
        /**
         * SELECT attr_id FROM `pms_attr` WHERE attr_id IN(?) AND search_type = 1
         */
        return baseMapper.listSearchAttrsByIds(attrIds);
    }


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVO attr) {
        AttrEntity attrEntity = new AttrEntity();
        //将attr与attrEntity中属性名相同的属性值全部复制到attrEntity中
        BeanUtils.copyProperties(attr,attrEntity);
        //1. 保存attr基本数据
        this.save(attrEntity);
        //只有规格参数且分组id不为空时才保存属性分组关联信息
        if(attr.getAttrId()!=null&&attr.getAttrGroupId()!=0&&attrEntity.getAttrType()!=null&&attrEntity.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            //2. 保存attr与attrGroup关联关系
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            //当attrEntity的信息保存后，attrId字段将会更新
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationService.save(relationEntity);
        }

    }

    @Transactional
    @Override
    public boolean updateAttr(AttrVO attr) {
        AttrEntity attrEntity = this.getById(attr.getAttrId());
        if(attr.getAttrType()!=attrEntity.getAttrType()) return false;

        attrEntity = new AttrEntity();
        //将attr与attrEntity中属性名相同的属性值全部复制到attrEntity中
        BeanUtils.copyProperties(attr,attrEntity);
        //1. 保存attr基本数据
        this.updateById(attrEntity);
        //2. 保存attr与attrGroup关联关系
        AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
        //当attrEntity的信息保存后，attrId字段将会更新
        relationEntity.setAttrId(attr.getAttrId());
        //当传入的attrGroupId为空时，将数据库中的attr_group_id字段的数据更新为0
        relationEntity.setAttrGroupId(attr.getAttrGroupId()==null?0:attr.getAttrGroupId());
        //用于判断attr_id是否在attr_attrgroup_relation表中是否有相关关联信息
        Integer count = attrAttrgroupRelationService.count(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attr.getAttrId()));
        if(count>0){
            attrAttrgroupRelationService.update(relationEntity,new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attrEntity.getAttrId()));
        }else{
            attrAttrgroupRelationService.save(relationEntity);
        }

        return true;
    }

    @Override
    public PageUtils queryByTypeAndCatelog(Map<String, Object> params, String attrType, Long catelogId) throws Exception {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper();
        if("base".equals(attrType)){//规格参数
            wrapper.eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        }else if("sale".equals(attrType)){//销售属性
            wrapper.eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_SALE);
        }else{
            throw new Exception("属性参数传入有误");
        }
        String key = (String)params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and((obj)->{
                obj.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        if(catelogId!=0){
            wrapper.eq("catelog_id",catelogId);
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();
        List<AttrRespVO> attrRespVOList = records.stream().map(attrEntity -> {
            AttrRespVO attrRespVO = new AttrRespVO();
            BeanUtils.copyProperties(attrEntity,attrRespVO);
            //设置分类和分组的名字
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attrEntity.getAttrId()));
            if(attrAttrgroupRelationEntity!=null){
                AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrAttrgroupRelationEntity.getAttrGroupId());
                if(attrGroupEntity!=null){
                    attrRespVO.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
            CategoryEntity categoryEntity = categoryService.getById(attrEntity.getCatelogId());
            if(categoryEntity!=null){
                attrRespVO.setCatelogName(categoryEntity.getName());
            }
            return attrRespVO;
        }).collect(Collectors.toList());

        pageUtils.setList(attrRespVOList);

        return pageUtils;
    }

    @Override
    public AttrRespVO getAttrVOById(Long attrId) {
        //根据attrId获取attrEntity
        AttrEntity attrEntity = this.getById(attrId);
        AttrRespVO attrRespVO = new AttrRespVO();
        BeanUtils.copyProperties(attrEntity,attrRespVO);

        //根据attrId获取一条AttrAttrgroupRelationEntity数据,设置分组信息
        AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationService.
                getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attrEntity.getAttrId()));
        if(relationEntity!=null&&relationEntity.getAttrGroupId()!=null&&relationEntity.getAttrGroupId()!=0){

            attrRespVO.setAttrGroupId(relationEntity.getAttrGroupId());
            AttrGroupEntity attrGroupEntity = attrGroupService.getById(relationEntity.getAttrGroupId());
            if(attrGroupEntity!=null){
                attrRespVO.setGroupName(attrGroupEntity.getAttrGroupName());
            }
        }
        //设置分类信息
        Long catelogId = attrEntity.getCatelogId();
        Long[] catelogPath = categoryService.getCatelogPath(catelogId);
        attrRespVO.setCatelogPath(catelogPath);
        return attrRespVO;
    }

}